import {LoadingOutlined, LockOutlined, SafetyCertificateOutlined, UserOutlined} from '@ant-design/icons';
import {useRequest} from '@umijs/hooks';
import {Button, Col, Form, Input, message, Modal, Row} from 'antd';
import React, {useState} from 'react';
import {getRsaSecretString} from '../../utils/encrypt';
import {fetchImageCode, loginFetch} from '../../utils/Request';
import {url} from '../../utils/url';
import './style.css';
import {useHistory} from 'react-router';
import cookie from 'react-cookies'
import errorCode from '../../utils/errorCode';


interface ImgCode {
    imgToken: string,
    imgSrc: string
}

interface LoginParams {
    username: string,
    password: string,
    imgToken: string,
    imgCode: string
}


export default function LoginForm() {

    const [data, setData] = useState<ImgCode>({imgToken: "", imgSrc: ""})

    const [errorMessage, seterrorMessage] = useState<string>("")

    const {loading, run} = useRequest(getImgCode);

    const submit = useRequest(onLogin, {
        manual: true,
        loadingDelay: 200
    })

    const history = useHistory();

    //请求验证码
    async function getImgCode() {
        try {
            const json = await fetchImageCode(url.GET_IMAGE_CODE)
            if (json.success) {
                setData({imgToken: json.imgToken, imgSrc: "data:image/jpeg;base64," + json.imgStr})
            } else {
                message.destroy();
                message.error(json.error);
                setData({imgToken: "", imgSrc: ""})
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
            setData({imgToken: "", imgSrc: ""})
        }

    }

    //点击提交的时候触发
    const onFinish = (values: any) => {
        const params: LoginParams = {
            username: getRsaSecretString(values.username) as string,
            password: getRsaSecretString(values.password) as string,
            imgToken: data.imgToken,
            imgCode: values.imgCode
        }
        submit.run(params)
    };

    //登录的异步请求
    async function onLogin(params: LoginParams) {
        try {
            const json = await loginFetch(url.LOGIN_URL, params)
            if (json.success) {
                cookie.remove("collegeToken");
                // cookie.remove("isLogin");
                cookie.save("collegeToken", json.token, {path: "/"});
                history.push("/home/index")
            } else if (json.code === errorCode.DANGER_PASSWORD) {
                Modal.error({
                    title: "弱密码警告",
                    content: "请先修改密码",
                    okText: "确定",
                    onOk: () => {
                        history.push("/changePassword");
                    }
                });
            } else if (json.code === errorCode.PASSWORD_AGING) {
                Modal.error({
                    title: "密码过期警告",
                    content: "请先修改密码",
                    okText: "确定",
                    onOk: () => {
                        history.push("/changePassword");
                    }
                });
            } else {
                seterrorMessage(json.error)
                getImgCode();
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    return (
        <Form
            className="login-form"
            name="basic"
            onFinish={onFinish}
        >
            <Form.Item
                name="username"
                rules={[{required: true, message: '请输入手机号！'},
                    {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！'},
                    {
                        max: 20,
                        message: '手机号长度过长'
                    }
                ]}
            >
                <Input type="text" prefix={<UserOutlined/>} placeholder="手机号码" size="large"/>
            </Form.Item>

            <Form.Item
                name="password"

                rules={
                    [{
                        required: true,
                        message: '请输入密码!'
                    }, {
                        pattern: /^[A-Za-z0-9!@#$%^&*?\(\) +=\[\]\{\}_<>,.;:'"-]+$/,
                        // pattern: /((\d)|([a-zA-Z])|([!@#$%^&*?\(\) +=\[\]\{\}_<>,.;:'"-]))/,
                        message: '密码包含非法字符！'
                    },
                        {
                            max: 20,
                            message: '密码长度过长'
                        }]}


            >
                <Input.Password prefix={<LockOutlined/>} placeholder="密码" size="large" autoComplete={"new-password"}
                                /> 
            </Form.Item>
            {/* onPaste={(e) => e.preventDefault()} onCopy={(e) => e.preventDefault()} 密码框粘贴事件 */}
            <Row>
                <Col span={15}>
                    <Form.Item name="imgCode" rules={[
                        {required: true, message: "请输入验证码"},

                        {
                            max: 20,
                            message: '验证码长度过长'
                        }
                    ]}>
                        <Input placeholder="请输入计算结果" prefix={<SafetyCertificateOutlined/>} size="large"/>
                    </Form.Item>
                </Col>
                <Col span={8} offset={1}>{
                    data.imgSrc === "" ? loading ? <div className={"img_code"}>
                            <LoadingOutlined/> 获取中
                        </div> : <div className={"img_code"} onClick={run}>
                            点击获取
                        </div> :
                        <img
                            onClick={run}
                            className={"img_code"}
                            src={data.imgSrc}
                            width={"100%"}
                            alt={"加载失败"}
                        />
                }
                </Col>
            </Row>

            <Form.Item>
                <small style={{color: "red"}}>{errorMessage}</small>
                <a
                    onClick={() => window.open('#/wisdomCollegeView/changePassword', '忘记密码')}
                    style={{float: "right"}}
                    rel="noopener noreferrer"

                >
                    忘记密码?
                </a>
                <Button loading={submit.loading} type="primary" htmlType="submit" className="login-button" size="large">
                    登录
                </Button>
            </Form.Item>
        </Form>
    );
}
